﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PostSharp.Aspects;
using System.Diagnostics;
using LuctecWS.DAL;
using LuctecWS.Core;

namespace LuctecWS.Aspect
{
    [Serializable]
    public sealed class LogExceptionAttribute : OnExceptionAspect
    {
        public override void OnException(MethodExecutionArgs args)
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                var log = new LuctecWS.DAL.log() { Date = DateTime.Now, Message = args.Exception.InnerException.Message, StackTrace = args.Exception.StackTrace };

                context.AddObject("log", log);

                context.SaveChanges();

                args.ReturnValue = args.Instance;

                Base res = args.ReturnValue as Base;

                errors error = context.errors.FirstOrDefault(e => args.Exception.InnerException.Message.Contains(e.Code));

                res.Error = new Error() { Code = context.log.ToList().Last().Id, FriendlyMessage = error != null ? error.FriendlyMessage : "" };

                args.FlowBehavior = FlowBehavior.Return;
            }
        }
    }
}